﻿using Microsoft.Win32;
using Set_File_Rw;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using TestFireBroadcastingHostPhone.Product;
using TestFireBroadcastingHostPhone.RecordData;
using TestFireBroadcastingHostPhone.Source;
using TestFireBroadcastingHostPhone.ViewModel;

namespace TestFireBroadcastingHostPhone
{
    public partial class ManualTest : UserControl
    {
        /// <summary>
        /// 满载打开的标志
        /// </summary>
        public bool open_load = false;
        /// <summary>
        /// 进入最小过流点的标志
        /// </summary>
        public bool enter_min = false;
        /// <summary>
        /// 进入最大过流点的标志
        /// </summary>
        public bool enter_max = false;
        /// <summary>
        /// 开启主电的标志
        /// </summary>
        public bool open_hostpower = false;
        /// <summary>
        /// 开启备电的标志
        /// </summary>
        public bool open_standbypower = false;
        /// <summary>
        /// 开启24V自动应急的标志
        /// </summary>
        public bool start24vol_enmergercy = false;
        /// <summary>
        /// 音频播放成功的标志
        /// </summary>
        private bool success_display = false;
        /// <summary>
        /// 应急启动的标志
        /// </summary>
        private bool emergency_start = false;
        /// <summary>
        /// 进入按键检测的标志
        /// </summary>
        private bool enter_key_check = false;
        /// <summary>
        /// 进入输出短路模式的标志
        /// </summary>
        private bool enter_short = false;
        /// <summary>
        /// 播放录音的标志
        /// </summary>
        private bool isRedioPlaying = false;
        /// <summary>
        /// 音频播放的标志
        /// </summary>
        private bool isPlaying = false;
        /// <summary>
        /// 视频播放的标志
        /// </summary>
        private bool isVideoPlaying = false;
        /// <summary>
        /// 音频播放默认的音量大小
        /// </summary>
        private double currentVolume = 0.5; // 初始音量设为最大
        /// <summary>
        /// 按键检测线程
        /// </summary>
        private Task? KeyCheckTask;
        /// <summary>
        /// 按键线程任务来源
        /// </summary>
        private CancellationTokenSource? KeyCheckTaskSourceToken;
        /// <summary>
        /// 音频播放的记录定时器
        /// </summary>
        private DispatcherTimer? VideoPlayingTimer;
        /// <summary>
        /// 查询功放网口定时器
        /// </summary>
        private DispatcherTimer? AmplifierCheckingTimer;
        /// <summary>
        /// 功放注册成功的标志
        /// </summary>
        private bool isRegisterSuccess = false;
        /// <summary>
        /// 网口检测进行标志
        /// </summary>
        private bool isCheckingAmplifier = false;
        public ManualTest()
        {
            InitializeComponent();
        }
        private void ManualTest_Loaded(object sender, RoutedEventArgs e)
        {
            VideoPlayingTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(100) };
            VideoPlayingTimer.Tick += VideoTimer_Tick;
            Txt_VideoSound.Text = $"音量: {currentVolume * 100:N1}%"; // 将音量显示为百分比形式
        }
        /// <summary>
        /// 打开产品串口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_OpenProductSerialPort_Click(object sender, RoutedEventArgs e)
        {
            string err_info = string.Empty;
            Button button = (Button)sender;
            if (!StaticInfo.funProduct.isProductSerialPortOpen)
            {
                StaticInfo.funProduct.Open_CommunicatePort(out err_info, 
                         AutoTestMV.autoTestMVInstance.Cmb_AutoTestSelect_SelectIndex,
                         SystemConfigMV.systemconfigMV.Cmb_HostPhoneSerialPort_SelectValue!,
                         SystemConfigMV.systemconfigMV.Cmb_485CommunicatePort_SelectValue!); //打开产品测试串口
                if (!string.IsNullOrEmpty(err_info))
                {
                    MessageBox.Show("打开产品串口错误", "打开串口", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    MessageBox.Show("打开产品串口成功", "打开串口", MessageBoxButton.OK, MessageBoxImage.Information);
                    button.Content = "关闭产品串口";
                }
            }
            else
            {
                StaticInfo.funProduct.Close_CommunicatePort(out err_info);
                if (!string.IsNullOrEmpty(err_info))
                {
                    MessageBox.Show("关闭产品串口错误", "关闭串口", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    MessageBox.Show("关闭产品串口成功", "关闭串口", MessageBoxButton.OK, MessageBoxImage.Information);
                    button.Content = "打开产品串口";
                }
            }
        }
        /// <summary>
        /// 开启/关闭主电
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Open_HostPower_Click(object sender, RoutedEventArgs e)
        {
            string err_info = string.Empty;
            Button button = (Button)sender;
            if (!string.IsNullOrEmpty(Txt_ManualTestResult.Text)) Txt_ManualTestResult.Clear();//清空显示
            StaticInfo.instrumentsControl.OpenACPower(SystemConfigMV.systemconfigMV.Cmb_ACPowerSelect_SelectValue,SystemConfigMV.systemconfigMV.Cmb_AN97002SerialPort_SelectValue!,out err_info);//打开程控交流源
            if (!string.IsNullOrEmpty(err_info))
            {
                AppendTextToTextBox("程控交流源打开失败：" + err_info);
                return;
            }
            if (!open_hostpower)
            {
                StaticInfo.frockControl.Exchange_ElectricRelay(3, true, out err_info);//控制工装开主电
                if (!string.IsNullOrEmpty(err_info))
                {
                    AppendTextToTextBox("主电开启失败：" + err_info);
                    return;
                }
                else
                {
                    AppendTextToTextBox("主电已打开");
                    open_hostpower = true;
                    button.Content = "关闭主电";
                }
            }
            else
            {
                StaticInfo.frockControl.Exchange_ElectricRelay(3, false, out err_info);//控制工装开主电
                if (!string.IsNullOrEmpty(err_info))
                {
                    AppendTextToTextBox("主电关闭失败：" + err_info);
                    return;
                }
                else
                {
                    AppendTextToTextBox("主电已关闭");
                    open_hostpower = false;
                    button.Content = "打开主电";
                }
            }
        }
        /// <summary>
        /// 开启/关闭备电
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Open_StandbyPower_Click(object sender, RoutedEventArgs e)
        {
            string err_info = string.Empty;
            Button button = (Button)sender;
            if (!string.IsNullOrEmpty(Txt_ManualTestResult.Text)) Txt_ManualTestResult.Clear();//清空显示
            StaticInfo.instrumentsControl.OpenACPower(SystemConfigMV.systemconfigMV.Cmb_ACPowerSelect_SelectValue, SystemConfigMV.systemconfigMV.Cmb_AN97002SerialPort_SelectValue!,out err_info);//打开程控交流源
            if (!string.IsNullOrEmpty(err_info))
            {
                AppendTextToTextBox("程控交流源打开失败：" + err_info);
                return;
            }
            if (!open_standbypower)
            {
                StaticInfo.frockControl.Exchange_ElectricRelay(2, true, out err_info);//控制工装开备电
                if (!string.IsNullOrEmpty(err_info))
                {
                    AppendTextToTextBox("备电开启失败：" + err_info);
                    return;
                }
                else
                {
                    AppendTextToTextBox("备电已打开");
                    open_standbypower = true;
                    button.Content = "关闭备电";
                }
            }
            else
            {
                StaticInfo.frockControl.Exchange_ElectricRelay(2, false, out err_info);//控制工装关备电
                if (!string.IsNullOrEmpty(err_info))
                {
                    AppendTextToTextBox("备电关闭失败：" + err_info);
                    return;
                }
                else
                {
                    AppendTextToTextBox("备电已关闭");
                    open_standbypower = false;
                    button.Content = "开启备电";
                }
            }
        }

        #region -- 性能测试
        /// <summary>
        /// 消音
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Silence_Control_Click(object sender, RoutedEventArgs e)
        {
            string err_info = string.Empty;
            if (StaticInfo.funProduct.isProductSerialPortOpen)
            {
                StaticInfo.funProduct.Silence_Control(out err_info);
                if (!string.IsNullOrEmpty(err_info))
                {
                    AppendTextToTextBox("广播主机消音失败：" + err_info);
                }
            }
            else
            {
                MessageBox.Show("产品串口未打开", "打开串口", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        /// <summary>
        /// 24V启动自动应急
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_24VoltageEmergency_Click(object sender, RoutedEventArgs e)
        {
            string err_info = string.Empty;
            Button button = (Button)sender;
            if (!string.IsNullOrEmpty(Txt_ManualTestResult.Text)) Txt_ManualTestResult.Clear();//清空显示
            if (!start24vol_enmergercy)
            {
                StaticInfo.frockControl.Exchange_ElectricRelay(1, true, out err_info);//控制工装开24V应急
                if (!string.IsNullOrEmpty(err_info))
                {
                    AppendTextToTextBox("24V应急开启失败：" + err_info);
                    return;
                }
                else
                {
                    AppendTextToTextBox("24V应急已开启");
                    start24vol_enmergercy = true;
                    button.Content = "关闭24V自动应急";
                }
            }
            else
            {
                StaticInfo.frockControl.Exchange_ElectricRelay(1, false, out err_info);//控制工装关24V应急
                if (!string.IsNullOrEmpty(err_info))
                {
                    AppendTextToTextBox("24V应急关闭失败：" + err_info);
                    return;
                }
                else
                {
                    AppendTextToTextBox("24V应急已关闭");
                    start24vol_enmergercy = false;
                    button.Content = "开启24V自动应急";
                }
            }
        }
        /// <summary>
        /// 带满载/关满载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_WithLoad_Click(object sender, RoutedEventArgs e)
        {
            string err_info = string.Empty;
            Button button = (Button)sender;
            if (!open_load)
            {
                StaticInfo.frockControl.Exchange_ElectricRelay(4, true, out err_info);//控制工装带满载
                if (!string.IsNullOrEmpty(err_info))
                {
                    AppendTextToTextBox("带满载失败：" + err_info);
                    return;
                }
                else
                {
                    AppendTextToTextBox("带满载成功");
                    open_load = true;//带满载成功
                    button.Content = "关闭满载";
                }
            }
            else
            {
                StaticInfo.frockControl.Exchange_ElectricRelay(4, false, out err_info);//控制工装关满载
                if (!string.IsNullOrEmpty(err_info))
                {
                    AppendTextToTextBox("关闭满载失败：" + err_info);
                    return;
                }
                else
                {
                    AppendTextToTextBox("关闭满载成功");
                    open_load = false;//带满载成功
                    button.Content = "开启满载";
                }
            }
        }
        /// <summary>
        /// 主机复位
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_AmplifierReset_Click(object sender, RoutedEventArgs e)
        {
            string err_info = string.Empty;
            if (StaticInfo.funProduct.isProductSerialPortOpen)
            {
                StaticInfo.funProduct.HostPhoneReset(out err_info);
                if (!string.IsNullOrEmpty(err_info))
                {
                    AppendTextToTextBox("广播主机复位错误：" + err_info);
                }
                else
                {
                    AppendTextToTextBox("广播主机已复位");
                }
            }
            else
            {
                MessageBox.Show("产品串口未打开", "打开串口", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        /// <summary>
        /// 查询功放状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_QureyAmplifierStatus_Click(object sender, RoutedEventArgs e)
        {
            string err_info = string.Empty;
            if (string.IsNullOrEmpty(Txt_ManualTestResult.Text)) Txt_ManualTestResult.Clear();//清空显示
            if (StaticInfo.funProduct.isProductSerialPortOpen)
            {
                StaticInfo.funProduct.QureyAmplifierStatus(1, out err_info);//查询主机后面的功放状态
                if (!string.IsNullOrEmpty(err_info))
                {
                    AppendTextToTextBox("读取功放状态失败：" + err_info);
                }
                else
                {
                    Thread.Sleep(500);
                    StaticInfo.funProduct.Function_QueryMicroStatus(out err_info);//查询话筒状态
                    if (!string.IsNullOrEmpty(err_info))
                    {
                        AppendTextToTextBox("读取功放状态失败：" + err_info);
                    }
                    else
                    {
                        AppendTextToTextBox("读取功放状态成功，当前状态为:"
                        + "主电：" + BoolExcangeString(StaticInfo.funProduct.Error_HostPower) + "；"
                        + "备电：" + BoolExcangeString(StaticInfo.funProduct.Error_StandbyPower) + "；"
                        + "输出：" + BoolExcangeString(StaticInfo.funProduct.Error_Output) + "；"
                        + "通讯：" + BoolExcangeString(StaticInfo.funProduct.Error_Communicate) + "；"
                        + "话筒：" + BoolExcangeString(StaticInfo.funProduct.Error_MicroPhone) + "；");
                    }
                }
            }
            else
            {
                MessageBox.Show("产品串口未打开", "打开串口", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        /// <summary>
        /// 最小过流点测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_OverCurrentMin_Click(object sender, RoutedEventArgs e)
        {
            Button button = (Button)sender;
            string err_info = string.Empty;
            if (!open_standbypower || !open_hostpower)
            {
                MessageBox.Show("请选择在主备电开启模式下进行过流测试!");
                return;
            }
            else
            {
                //如果没有进入最小过流测试
                if (!enter_min)
                {
                    if (open_load)
                    {
                        StaticInfo.frockControl.Exchange_ElectricRelay(5, true, out err_info);//控制工装开启最小过流测试
                        if (!string.IsNullOrEmpty(err_info))
                        {
                            AppendTextToTextBox("开启最小过流测试失败：" + err_info);
                            return;
                        }
                        else
                        {
                            AppendTextToTextBox("开启最小过流测试成功");
                            enter_min = true;//进入最小过流
                            button.Content = "关闭最小过流";
                        }
                    }
                    else
                    {
                        MessageBox.Show("请在带满载的状态下进行过流测试!");
                    }
                }
                else
                {
                    StaticInfo.frockControl.Exchange_ElectricRelay(5, false, out err_info);//控制工装关闭最小过流测试
                    if (!string.IsNullOrEmpty(err_info))
                    {
                        AppendTextToTextBox("关闭最小过流测试失败：" + err_info);
                        return;
                    }
                    else
                    {
                        AppendTextToTextBox("关闭最小过流测试成功");
                        enter_min = false;//退出最小过流
                        button.Content = "开启最小过流";
                    }
                }
            }
        }
        /// <summary>
        /// 最大过流点测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_OverCurrentMax_Click(object sender, RoutedEventArgs e)
        {
            string err_info = string.Empty;
            Button button = (Button)sender;
            if (!open_standbypower || !open_hostpower)
            {
                MessageBox.Show("请选择在主备电开启模式下进行过流测试!");
                return;
            }
            else
            {
                //如果没有进入最大过流测试
                if (!enter_max)
                {
                    if (open_load)
                    {
                        StaticInfo.frockControl.Exchange_ElectricRelay(6, true, out err_info);//控制工装开启最大过流测试
                        if (!string.IsNullOrEmpty(err_info))
                        {
                            AppendTextToTextBox("开启最大过流测试失败：" + err_info);
                            return;
                        }
                        else
                        {
                            AppendTextToTextBox("开启最大过流测试成功");
                            enter_max = true;//进入最大过流
                            button.Content = "关闭最大过流";
                        }
                    }
                    else
                    {
                        MessageBox.Show("请在带满载的状态下进行过流测试!");
                    }
                }
                else
                {
                    StaticInfo.frockControl.Exchange_ElectricRelay(6, false, out err_info);//控制工装开启最大过流测试
                    if (!string.IsNullOrEmpty(err_info))
                    {
                        AppendTextToTextBox("关闭最大过流测试失败：" + err_info);
                        return;
                    }
                    else
                    {
                        AppendTextToTextBox("关闭最大过流测试成功");
                        enter_max = false;//退出最大过流
                        button.Content = "开启最大过流";
                    }
                }
            }
        }
        /// <summary>
        /// 过压恢复测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_BeyondAndRestoreVoltage_Click(object sender, RoutedEventArgs e)
        {
            string err_info = string.Empty;
            string default_file_path = Directory.GetCurrentDirectory() + "\\RecordData\\RelatedRecord.ini";
            if (!open_standbypower || !open_hostpower)
            {
                MessageBox.Show("请选择在主备电开启模式下进行过压恢复测试!");
                return;
            }
            else
            {
                if (string.IsNullOrEmpty(Txt_ManualTestResult.Text)) Txt_ManualTestResult.Clear();//清空显示
                if ((StaticInfo.instrumentsControl.ACPowerPort != null))
                {
                    StaticInfo.instrumentsControl.Beyond_VoltageMaxTest(SystemConfigMV.systemconfigMV.Cmb_ACPowerSelect_SelectValue, SystemConfigMV.systemconfigMV.HostPowerBeyondVoltage, out err_info);//过压设置
                    if (!string.IsNullOrEmpty(err_info))
                    {
                        AppendTextToTextBox("主电过压设置失败：" + err_info);
                    }
                    else
                    {
                        AppendTextToTextBox("主电过压设置成功");
                        Set_Data_Rw.Write(SystemConfigMV.configpath, default_file_path, "主电过压", SystemConfigMV.systemconfigMV.HostPowerBeyondVoltage, out err_info);
                    }
                    Thread.Sleep(6000);
                    StaticInfo.instrumentsControl.Restore_VoltageTest(SystemConfigMV.systemconfigMV.Cmb_ACPowerSelect_SelectValue, out err_info);//恢复设置
                    if (!string.IsNullOrEmpty(err_info))
                    {
                        AppendTextToTextBox("主电恢复设置失败：" + err_info);
                    }
                    else
                    {
                        AppendTextToTextBox("主电恢复设置成功");
                        Set_Data_Rw.Write(SystemConfigMV.configpath, default_file_path, "主电恢复", SystemConfigMV.systemconfigMV.HostPowerRestoreVoltage, out err_info);
                    }
                    Thread.Sleep(2000);
                    StaticInfo.instrumentsControl.Host220_VoltageTest(SystemConfigMV.systemconfigMV.Cmb_ACPowerSelect_SelectValue, out err_info);//恢复220设置
                    if (!string.IsNullOrEmpty(err_info))
                    {
                        AppendTextToTextBox("主电恢复220设置失败：" + err_info);
                    }
                    else
                    {
                        AppendTextToTextBox("主电恢复220设置成功");
                    }
                }
            }
        }
        /// <summary>
        /// 输出短路测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_ShortOutput_Click(object sender, RoutedEventArgs e)
        {
            string err_info = string.Empty;
            Button button = (Button)sender;
            if (!open_standbypower || !open_hostpower)
            {
                MessageBox.Show("请选择在主备电开启模式下进行输出短路测试!");
                return;
            }
            else
            {
                if (!enter_short)
                {
                    StaticInfo.frockControl.Set_LEDStatus(0, 1, out err_info);//开启输出短路测试
                    if (!string.IsNullOrEmpty(err_info))
                    {
                        AppendTextToTextBox("开启输出短路测试失败：" + err_info);
                    }
                    else
                    {
                        AppendTextToTextBox("开启输出短路测试成功");
                        enter_short = true;
                        button.Content = "关闭输出短路";
                    }
                }
                else
                {
                    StaticInfo.frockControl.Set_LEDStatus(0, 0, out err_info);//关闭输出短路测试
                    if (!string.IsNullOrEmpty(err_info))
                    {
                        AppendTextToTextBox("关闭输出短路测试失败：" + err_info);
                    }
                    else
                    {
                        AppendTextToTextBox("关闭输出短路测试成功");
                        enter_short = false;
                        button.Content = "开启输出短路";
                    }
                }
            }
        }
        /// <summary>
        /// 播放U盘中文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_DisplayVoiceSource_Click(object sender, RoutedEventArgs e)
        {
            string err_info = string.Empty;
            Button button = (Button)sender;
            if (StaticInfo.funProduct.isProductSerialPortOpen)
            {
                if (!success_display)
                {
                    StaticInfo.funProduct.Function_DisplayVideos(out err_info, 0, true);
                    if (!string.IsNullOrEmpty(err_info))
                    {
                        AppendTextToTextBox("播放音频文件失败：" + err_info);
                    }
                    else
                    {
                        success_display = true;//音频播放成功
                        button.Content = "停止";
                        AppendTextToTextBox("播放音频文件成功");
                    }
                }
                else
                {
                    StaticInfo.funProduct.Function_DisplayVideos(out err_info, 0, false);//停止播放音频
                    if (!string.IsNullOrEmpty(err_info))
                    {
                        AppendTextToTextBox("停止播放音频文件失败：" + err_info);
                    }
                    else
                    {
                        AppendTextToTextBox("停止播放音频文件成功");
                        success_display = false;//音频停止播放成功
                        button.Content = "播放";
                    }
                }
            }
            else
            {
                MessageBox.Show("产品串口未打开", "打开串口", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        #endregion //性能测试

        #region -- 通讯显示测试
        /// <summary>
        /// 自检测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_CheckSelf_Click(object sender, RoutedEventArgs e)
        {
            string err_info = string.Empty;
            if (!open_standbypower || !open_hostpower)
            {
                MessageBox.Show("请选择在主备电开启模式下进行自检测试!");
                return;
            }
            else
            {
                if (StaticInfo.funProduct.isProductSerialPortOpen)
                {
                    AppendTextToTextBox("正在进行自检中!");
                    StaticInfo.funProduct.CheckSelf(out err_info, Convert.ToByte(SystemConfigMV.systemconfigMV.Text_CheckSelfTimer));
                    if (string.IsNullOrEmpty(err_info))
                    {
                        Thread.Sleep(Convert.ToByte(SystemConfigMV.systemconfigMV.Text_CheckSelfTimer) * 1000);//等待自检完成后
                        AppendTextToTextBox("自检完成!");
                    }
                    else
                    {
                        AppendTextToTextBox("产品自检失败,错误信息：" + err_info);
                    }
                }
                else
                {
                    MessageBox.Show("产品串口未打开", "打开串口", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
        /// <summary>
        /// 匹配攻放测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_MatchingAmplifier_Click(object sender, RoutedEventArgs e)
        {
            string err_info = string.Empty;
            if (StaticInfo.funProduct.isProductSerialPortOpen)
            {
                StaticInfo.funProduct.RegisterAmplifier(3, out err_info);//先注册功放
                if (!string.IsNullOrEmpty(err_info))
                {
                    AppendTextToTextBox("功放注册失败,错误信息:" + err_info);
                    isCheckingAmplifier = false;
                }
                else
                {
                    AppendTextToTextBox("功放注册成功!");
                    isRegisterSuccess = true;
                }
            }
            else
            {
                MessageBox.Show("产品串口未打开", "打开串口", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        /// <summary>
        /// 网口检测
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_CheckInternetIO_Click(object sender, RoutedEventArgs e)
        {
            string err_info = string.Empty;
            Button button = (Button)sender;
            if (!isRegisterSuccess)
            {
                MessageBox.Show("未注册功放", "网口检测", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            else
            {
                if (!isCheckingAmplifier)
                {
                    AmplifierCheckingTimer = new DispatcherTimer();
                    AmplifierCheckingTimer.Interval = TimeSpan.FromSeconds(2);
                    AmplifierCheckingTimer.Tick += AmplifierCheckingTimerTick;
                    AmplifierCheckingTimer.Start();
                    isCheckingAmplifier = true;
                    button.Content = "结束检测";
                }
                else
                {
                    AmplifierCheckingTimer?.Stop();
                    isCheckingAmplifier = false;
                    button.Content = "网口检测";
                }
            }
        }
        /// <summary>
        /// 网口检测定时器任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AmplifierCheckingTimerTick(object? sender, EventArgs e)
        {
            string err_info = string.Empty;
            if (!StaticInfo.funProduct.isProductSerialPortOpen) return;
            StaticInfo.funProduct.QureyAmplifierStatus(1, out err_info);//查询通过网口1注册的功放状态
            this.Dispatcher.Invoke(() =>
            {
                if (!string.IsNullOrEmpty(err_info))
                {
                    AppendTextToTextBox("查询注册功放错误,错误信息：" + err_info);
                }
                else
                {
                    AppendTextToTextBox("读取网口1成功,当前状态为:"
                    + "主电：" + BoolExcangeString(StaticInfo.funProduct.Error_HostPower) + "；"
                    + "备电：" + BoolExcangeString(StaticInfo.funProduct.Error_StandbyPower) + "；"
                    + "输出：" + BoolExcangeString(StaticInfo.funProduct.Error_Output) + "；"
                    + "通讯：" + BoolExcangeString(StaticInfo.funProduct.Error_Communicate));
                }
            });
            Thread.Sleep(500);
            StaticInfo.frockControl.Set_LEDStatus(1, 1, out err_info);//网口控制继电器，切换到2网口
            StaticInfo.funProduct.QureyAmplifierStatus(1, out err_info);//查询通过网口2注册的功放状态
            this.Dispatcher.Invoke(() =>
            {
                if (!string.IsNullOrEmpty(err_info))
                {
                    AppendTextToTextBox("查询注册功放错误,错误信息：" + err_info);
                }
                else
                {
                    AppendTextToTextBox("读取网口2成功,当前状态为:"
                    + "主电：" + BoolExcangeString(StaticInfo.funProduct.Error_HostPower) + "；"
                    + "备电：" + BoolExcangeString(StaticInfo.funProduct.Error_StandbyPower) + "；"
                    + "输出：" + BoolExcangeString(StaticInfo.funProduct.Error_Output) + "；"
                    + "通讯：" + BoolExcangeString(StaticInfo.funProduct.Error_Communicate));
                }
            });
            Thread.Sleep(500);
            StaticInfo.frockControl.Set_LEDStatus(1, 0, out err_info);//网口控制继电器，切换回1网口
        }
        /// <summary>
        /// 面板应急
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_EmergencyStart24Voltage_Click(object sender, RoutedEventArgs e)
        {
            string err_info = string.Empty;
            Button button = (Button)sender;
            if (StaticInfo.funProduct.isProductSerialPortOpen)
            {
                if (!emergency_start)
                {
                    StaticInfo.funProduct.Manual_Emergency(out err_info, Productions.EmergencyStatus.Start);//应急启动
                    if (!string.IsNullOrEmpty(err_info))
                    {
                        AppendTextToTextBox("应急启动失败,错误信息：" + err_info);
                    }
                    else
                    {
                        AppendTextToTextBox("应急启动成功");
                        emergency_start = true;
                        button.Content = "应急停止";
                    }
                }
                else
                {
                    StaticInfo.funProduct.Manual_Emergency(out err_info, Productions.EmergencyStatus.Stop);//应急停止
                    if (!string.IsNullOrEmpty(err_info))
                    {
                        AppendTextToTextBox("应急停止失败,错误信息：" + err_info);
                    }
                    else
                    {
                        AppendTextToTextBox("应急停止成功");
                        emergency_start = false;
                        button.Content = "应急启动";
                    }
                }
            }
            else
            {
                MessageBox.Show("产品串口未打开", "打开串口", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        /// <summary>
        /// 按键映射表
        /// </summary>
        public static readonly (int index, int keyNumberIndex, int bitIndex, string keyName)[] keyMapping =
        {
            (0, 1, 1, "通播按键"),
            (1, 0, 5, "按键1"),
            (2, 1, 6, "按键2"),
            (3, 1, 0, "按键3"),
            (4, 0, 6, "返回按键"),
            (5, 1, 3, "应急按键"),
            (6, 0, 0, "按键4"),
            (7, 1, 4, "按键5"),
            (8, 0, 2, "按键6"),
            (9, 0, 1, "按键0"),
            (10, 1, 5, "消音按键"),
            (11, 1, 7, "按键7"),
            (12, 1, 2, "按键8"),
            (13, 0, 4, "按键9"),
            (14, 0, 3, "确认按键")
        };
        /// <summary>
        /// 按键检测
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_KeyCheck_Click(object sender, RoutedEventArgs e)
        {
            string err_info = string.Empty;
            Button button = (Button)sender;
            if (!StaticInfo.funProduct.isProductSerialPortOpen) return;
            if (!string.IsNullOrEmpty(Txt_ManualTestResult.Text)) Txt_ManualTestResult.Clear();//清空显示
            if (!enter_key_check)
            {
                button.Content = "进行中";
                Window ownerWindow = Window.GetWindow(this);
                Window KeyCheckWindow = new Window
                {
                    Width = 300,
                    Height = 200,
                    Title = "按键检测",
                    WindowStartupLocation = WindowStartupLocation.CenterScreen,
                    Owner = ownerWindow, // 设置拥有者，使其成为模态窗口
                    WindowStyle = WindowStyle.ToolWindow, // 设置窗口样式
                    ShowInTaskbar = false // 不在任务栏显示
                };
                ProgressBar progressBar = new ProgressBar
                {
                    Width = 250,
                    Height = 20,
                    HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment = VerticalAlignment.Center,
                    Maximum = 15, // 设置最大值为15
                    Value = 0
                };
                enter_key_check = true;
                Grid grid = new Grid();
                grid.Children.Add(progressBar);
                KeyCheckWindow.Content = grid;
                KeyCheckWindow.Show();
                // 注册窗口关闭事件
                KeyCheckWindow.Closed += (s, ev) => { KeyCheckTaskSourceToken?.Cancel(); };
                KeyCheckTaskSourceToken = new CancellationTokenSource();
                KeyCheckTask = Task.Run(() => Task_KeyCheck(KeyCheckTaskSourceToken.Token, progressBar, KeyCheckWindow, button));
            }
            else
            {
                button.Content = "按键检测";
                enter_key_check = false;
                KeyCheckTaskSourceToken?.Cancel();
            }
        }
        /// <summary>
        /// 按键测试线程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Task_KeyCheck(CancellationToken cancellationToken, ProgressBar progressBar, Window window, Button button)
        {
            string err_info = string.Empty;
            int receivedKeysCount = 0;
            var detectedKeys = new HashSet<int>(); // 用于跟踪已检测到的按键
            try
            {
                while (!cancellationToken.IsCancellationRequested && receivedKeysCount < 15)
                {
                    foreach (var (index, keyNumberIndex, bitIndex, keyName) in keyMapping)
                    {
                        Thread.Sleep(500);
                        // 检查按键是否已经检测过
                        if (detectedKeys.Contains(index)) continue;
                        StaticInfo.funProduct.KeyCheck(out err_info);
                        if (!string.IsNullOrEmpty(err_info))
                        {
                            Dispatcher.Invoke(() => { AppendTextToTextBox("按键查询错误: " + err_info); });
                            continue;
                        }
                        StaticInfo.funProduct.Key_Value[index] = IsKeyStatusSet(StaticInfo.funProduct.KeyNumber[keyNumberIndex], bitIndex);
                        // 检查按键状态是否为 Effective
                        if (StaticInfo.funProduct.Key_Value[index] == FunProduct.Key_Status.Effective)
                        {
                            detectedKeys.Add(index);
                            receivedKeysCount++;
                            Dispatcher.Invoke(() => { progressBar.Value++; });
                        }
                    }
                }
            }
            catch (OperationCanceledException)
            {
                Dispatcher.Invoke(() => { AppendTextToTextBox("检测中止: "); });
            }
            finally
            {
                Dispatcher.Invoke(() =>
                {
                    if (window != null)
                    {
                        window.Close();
                    }
                    button.Content = "按键检测";
                    enter_key_check = false;
                    StringBuilder result = new StringBuilder();
                    foreach (var (index, _, _, keyName) in keyMapping)
                    {
                        result.AppendLine($"{keyName}: {KeyStatusToString(StaticInfo.funProduct.Key_Value[index])}");
                    }
                    AppendTextToTextBox("按键查询结束: " + result.ToString());
                });
            }
        }
        /// <summary>
        /// 按键字符串显示
        /// </summary>
        /// <param name="status">状态</param>
        /// <returns></returns>
        public static string KeyStatusToString(FunProduct.Key_Status status)
        {
            switch (status)
            {
                case FunProduct.Key_Status.Effective:
                    return "有效";
                case FunProduct.Key_Status.Invalid:
                    return "无效";
                default:
                    return "未知状态";
            }
        }

        //for (int i = 0; i < 15; i++)
        //{
        //    StaticInfo.funProduct.Key_Value[i] = IsKeyStatusSet(StaticInfo.funProduct.KeyNumber[i / 8], i % 8);
        //}
        //StaticInfo.funProduct.Key_Value[0] = IsKeyStatusSet(StaticInfo.funProduct.KeyNumber[1], 1);//得到通播按键有效值
        //StaticInfo.funProduct.Key_Value[1] = IsKeyStatusSet(StaticInfo.funProduct.KeyNumber[0], 5);//得到按键1有效值
        //StaticInfo.funProduct.Key_Value[2] = IsKeyStatusSet(StaticInfo.funProduct.KeyNumber[1], 6);//得到按键2有效值
        //StaticInfo.funProduct.Key_Value[3] = IsKeyStatusSet(StaticInfo.funProduct.KeyNumber[1], 0);//得到按键3有效值
        //StaticInfo.funProduct.Key_Value[4] = IsKeyStatusSet(StaticInfo.funProduct.KeyNumber[0], 6);//得到返回按键有效值
        //StaticInfo.funProduct.Key_Value[5] = IsKeyStatusSet(StaticInfo.funProduct.KeyNumber[1], 3);//得到应急按键有效值
        //StaticInfo.funProduct.Key_Value[6] = IsKeyStatusSet(StaticInfo.funProduct.KeyNumber[0], 0);//得到按键4有效值
        //StaticInfo.funProduct.Key_Value[7] = IsKeyStatusSet(StaticInfo.funProduct.KeyNumber[1], 4);//得到按键5有效值
        //StaticInfo.funProduct.Key_Value[8] = IsKeyStatusSet(StaticInfo.funProduct.KeyNumber[0], 2);//得到按键6有效值
        //StaticInfo.funProduct.Key_Value[9] = IsKeyStatusSet(StaticInfo.funProduct.KeyNumber[0], 1);//得到按键0有效值
        //StaticInfo.funProduct.Key_Value[10] = IsKeyStatusSet(StaticInfo.funProduct.KeyNumber[1], 5);//得到消音按键有效值
        //StaticInfo.funProduct.Key_Value[11] = IsKeyStatusSet(StaticInfo.funProduct.KeyNumber[1], 7);//得到按键7有效值
        //StaticInfo.funProduct.Key_Value[12] = IsKeyStatusSet(StaticInfo.funProduct.KeyNumber[1], 2);//得到按键8有效值
        //StaticInfo.funProduct.Key_Value[13] = IsKeyStatusSet(StaticInfo.funProduct.KeyNumber[0], 4);//得到按键9有效值
        //StaticInfo.funProduct.Key_Value[14] = IsKeyStatusSet(StaticInfo.funProduct.KeyNumber[0], 3);//得到确认按键有效值
        /// <summary>
        /// 屏蔽功放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_ShieldAmplifier_Click(object sender, RoutedEventArgs e)
        {
            string err_info = string.Empty;
            if (StaticInfo.funProduct.isProductSerialPortOpen)
            {
                StaticInfo.funProduct.RegisterAmplifier(1, out err_info);//注册1个功放，代表网口连接的将功放屏蔽
                if (!string.IsNullOrEmpty(err_info))
                {
                    AppendTextToTextBox("功放屏蔽失败,错误信息:" + err_info);
                }
                else
                {
                    AppendTextToTextBox("功放屏蔽成功");
                }
            }
            else
            {
                MessageBox.Show("产品串口未打开", "打开串口", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        /// <summary>
        /// 命令测试控制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_ShieldAreaContorl_Click(object sender, RoutedEventArgs e)
        {
            string err_info = string.Empty;
            if (StaticInfo.funProduct.isProductSerialPortOpen)
            {
                switch (SystemConfigMV.systemconfigMV.Cmb_AutoTestCmdConfig_SelectedIndex)
                {
                    case (int)SystemConfigMV.Test_CmdConfig.Cmd_ShieldControlAndAddress:
                        StaticInfo.funProduct.Cmd_TestConfig(0, out err_info);//屏蔽区域控制和本机地址
                        if (!string.IsNullOrEmpty(err_info))
                        {
                            AppendTextToTextBox("屏蔽区域控制和本机地址失败");
                        }
                        else
                        {
                            AppendTextToTextBox("屏蔽区域控制和本机地址成功");
                        }
                        break;
                    case (int)SystemConfigMV.Test_CmdConfig.Cmd_ShieldControl_SaveAddress:
                        StaticInfo.funProduct.Cmd_TestConfig(8, out err_info);//屏蔽区域控制和保留本机地址
                        if (!string.IsNullOrEmpty(err_info))
                        {
                            AppendTextToTextBox("屏蔽区域控制保留本机地址失败");
                        }
                        else
                        {
                            AppendTextToTextBox("屏蔽区域控制保留本机地址成功");
                        }
                        break;
                    case (int)SystemConfigMV.Test_CmdConfig.Cmd_SaveControlAndAddress:
                        StaticInfo.funProduct.Cmd_TestConfig(10, out err_info);//保留区域控制和本机地址
                        if (!string.IsNullOrEmpty(err_info))
                        {
                            AppendTextToTextBox("保留区域控制和本机地址失败");
                        }
                        else
                        {
                            AppendTextToTextBox("保留区域控制和本机地址成功");
                        }
                        break;
                    case (int)SystemConfigMV.Test_CmdConfig.Cmd_NoneConfig:
                        break;
                    default:
                        break;
                }
            }
            else
            {
                MessageBox.Show("产品串口未打开", "打开串口", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        /// <summary>
        /// 刷字库：更新应急的音源
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Btn_UpdateAudioSource_Click(object sender, RoutedEventArgs e)
        {
            string err_info = string.Empty;
            string voice_source = Directory.GetCurrentDirectory() + "\\Videos\\Bundle_EMER0.bin";
            bool result_update = false;
            if (StaticInfo.funProduct.isProductSerialPortOpen)
            {
                try
                {
                    Grd_ManualTest.IsEnabled = false;
                    await Task.Run(() => { StaticInfo.funProduct.Function_SplitIntoFrames(out err_info, out result_update, voice_source); });
                    Grd_ManualTest.IsEnabled = true;
                    if (!string.IsNullOrEmpty(err_info))
                    {
                        AppendTextToTextBox("字库刷新失败: " + err_info);
                    }
                    else
                    {
                        if (result_update)
                        {
                            AppendTextToTextBox("字库更新成功");
                        }
                        else
                        {
                            AppendTextToTextBox("字库更新未执行");
                        }
                    }
                }
                catch (Exception ex)
                {
                    AppendTextToTextBox("发生异常: " + ex.Message);
                }
            }
            else
            {
                MessageBox.Show("产品串口未打开", "打开串口", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        /// <summary>
        /// 查询本机地址
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_QureySelfAddress_Click(object sender, RoutedEventArgs e)
        {
            string err_info = string.Empty;
            byte address = 0;
            if (StaticInfo.funProduct.isProductSerialPortOpen)
            {
                address = StaticInfo.funProduct.Qurey_AmplifierAddress(out err_info);
                if (!string.IsNullOrEmpty(err_info))
                {
                    AppendTextToTextBox("查询音源板地址,错误信息:" + err_info);
                }
                else
                {
                    AppendTextToTextBox("当前音源板地址为:" + address.ToString());
                }
            }
            else
            {
                MessageBox.Show("产品串口未打开", "打开串口", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        #endregion

        #region --录音测试
        /// <summary>
        /// 播放/暂停录音
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_DisplayRedio_Click(object sender, RoutedEventArgs e)
        {
            string err_info = string.Empty;
            Button button = (Button)sender;
            if (StaticInfo.funProduct.isProductSerialPortOpen)
            {
                if (!isRedioPlaying)
                {
                    StaticInfo.funProduct.Function_Display_Redio(1, out err_info);
                    if (!string.IsNullOrEmpty(err_info))
                    {
                        AppendTextToTextBox("播放录音错误,错误信息:" + err_info);
                    }
                    else
                    {
                        AppendTextToTextBox("播放录音成功");
                        button.Content = "⏸暂停录音";
                        isRedioPlaying = true;
                    }
                }
                else
                {
                    StaticInfo.funProduct.Function_Display_Redio(0, out err_info);
                    if (!string.IsNullOrEmpty(err_info))
                    {
                        AppendTextToTextBox("暂停录音错误,错误信息:" + err_info);
                    }
                    else
                    {
                        AppendTextToTextBox("录音暂停成功");
                        button.Content = "▶播放录音";
                        isRedioPlaying = false;
                    }
                }
            }
            else
            {
                MessageBox.Show("产品串口未打开", "打开串口", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        /// <summary>
        /// 删除录音
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_RedioDeleteClick(object sender, RoutedEventArgs e)
        {
            string err_info = string.Empty;
            if (StaticInfo.funProduct.isProductSerialPortOpen)
            {
                StaticInfo.funProduct.Function_Delete_Redio(out err_info);//删除录音
                if (!string.IsNullOrEmpty(err_info))
                {
                    AppendTextToTextBox("删除录音错误,错误信息:" + err_info);
                }
                else
                {
                    AppendTextToTextBox("录音删除成功");
                }
            }
            else
            {
                MessageBox.Show("产品串口未打开", "打开串口", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        #endregion

        #region -- 音频切换功能测试
        /// <summary>
        /// 音频播放时间记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void VideoTimer_Tick(object? sender, EventArgs e)
        {
            if (mediaElement.NaturalDuration.HasTimeSpan)
            {
                Slid.Value = mediaElement.Position.TotalSeconds;
                string formattedTime = mediaElement.Position.ToString(@"hh\:mm\:ss");
                Txt_PlayTime.Text = formattedTime;
            }
        }
        /// <summary>
        /// 进度条拖动播放进度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void slid_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            mediaElement.Position = TimeSpan.FromSeconds(Slid.Value);
        }
        /// <summary>
        /// 打开音频文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_OpenVideosPath_Click(object sender, RoutedEventArgs e)
        {
            string filePath = string.Empty;
            string fileExtension = string.Empty;
            if (AutoTestConfig.Default.测试人员 == "张文文")
            {
                filePath = Directory.GetCurrentDirectory() + "\\Videos\\videoZww.mp4";
                fileExtension = Path.GetExtension(filePath).ToLower();
            }
            else
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Filter = "Audio Files|*.mp3;*.mp4";// 设置过滤器，只显示 mp3 和 mp4 文件
                if (openFileDialog.ShowDialog() == true)
                {
                    filePath = openFileDialog.FileName;
                    fileExtension = Path.GetExtension(filePath).ToLower();
                    Txt_PathVedios.Text = filePath;
                }
            }
            if (fileExtension == ".mp4")
            {
                Window videoWindow = new Window
                {
                    Width = 500,
                    Height = 300,
                    Title = "Video",
                    WindowStartupLocation = WindowStartupLocation.CenterScreen
                };
                MediaElement mediaElement = new MediaElement
                {
                    LoadedBehavior = MediaState.Manual,
                    UnloadedBehavior = MediaState.Stop,
                    Stretch = Stretch.Fill
                };
                mediaElement.Source = new Uri(filePath);// 自动播放
                mediaElement.Loaded += (s, ev) => mediaElement.Play();// 鼠标单击控制播放和暂停
                mediaElement.MouseLeftButtonDown += (s, ev) =>
                {
                    if (mediaElement.CanPause && mediaElement.Position != null)
                    {
                        if (mediaElement.Position.TotalSeconds > 0)
                        {
                            if (!isVideoPlaying)
                            {
                                isVideoPlaying = true;
                                mediaElement.Play();
                            }
                            else
                            {
                                isVideoPlaying = false;
                                mediaElement.Pause();
                            }
                        }
                    }
                };
                Grid grid = new Grid();
                grid.Children.Add(mediaElement);
                videoWindow.Content = grid;
                videoWindow.Show();
            }
            else
            {
                MediaElement mediaElement = new MediaElement
                {
                    LoadedBehavior = MediaState.Manual,
                    UnloadedBehavior = MediaState.Stop
                };
                try
                {
                    mediaElement.Source = new Uri(filePath);
                    this.Content = mediaElement;
                }
                catch (Exception ex) 
                {
                    MessageBox.Show($"播放失败：{ex.Message}", "播放失败", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
        /// <summary>
        /// 播放/暂停音频
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_StartAndSuspendPlaying_Click(object sender, RoutedEventArgs e)
        {
            if (mediaElement.Source != null)
            {
                if (!isPlaying)
                {
                    isPlaying = true;
                    mediaElement.Play();
                    Btn_StartAndSuspendPlaying.Content = "暂停";
                }
                else
                {
                    isPlaying = false;
                    mediaElement.Pause();
                    Btn_StartAndSuspendPlaying.Content = "播放";
                }
            }
            else
            {
                MessageBox.Show("请选择音频文件!");
            }
        }
        /// <summary>
        /// 停止播放音频
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_StopPlaying_Click(object sender, RoutedEventArgs e)
        {
            if (mediaElement.Source != null)
            {
                mediaElement.Stop();
                isPlaying = false;
                Btn_StartAndSuspendPlaying.Content = "播放";
            }
            else
            {
                MessageBox.Show("请选择音频文件!");
            }
        }
        /// <summary>
        /// 获取音频文件时长
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void VideoMedia_MediaOpened(object sender, RoutedEventArgs e)
        {
            TimeSpan duration = mediaElement.NaturalDuration.TimeSpan;
            Slid.Maximum = duration.TotalSeconds;
            TimeSpan timeSpan = TimeSpan.FromSeconds(Slid.Maximum);
            Txt_TotalTime.Text = timeSpan.ToString(@"hh\:mm\:ss");
            VideoPlayingTimer?.Start();
        }
        /// <summary>
        /// 拖动进度条改变音频进度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Slid_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (!Slid.IsMouseOver) return;
            mediaElement.Position = TimeSpan.FromSeconds(Slid.Value);
        }
        /// <summary>
        /// 音频音量增大
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_TrunUpSound_Click(object sender, RoutedEventArgs e)
        {
            if (currentVolume < 1.0)
            {
                currentVolume += 0.1; // 每次增加0.1
                mediaElement.Volume = currentVolume;
                Txt_VideoSound.Text = $"音量: {currentVolume * 100:N1}%"; // 将音量显示为百分比形式
            }
        }
        /// <summary>
        /// 音频音量减小
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_TrunDownSound_Click(object sender, RoutedEventArgs e)
        {
            if (currentVolume > 0.0)
            {
                currentVolume -= 0.1; // 每次减少0.1
                mediaElement.Volume = currentVolume;
                Txt_VideoSound.Text = $"音量: {currentVolume * 100:N1}%"; // 将音量显示为百分比形式
            }
        }
        /// <summary>
        /// 广播主机监听音量调大
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_TrunUpMornitorSource_Click(object sender, RoutedEventArgs e)
        {
            string err_info = string.Empty;
            if (StaticInfo.funProduct.isProductSerialPortOpen)
            {
                StaticInfo.funProduct.Function_Adjust_MornitorVolume(1, out err_info);//监听音量调大
                if (!string.IsNullOrEmpty(err_info))
                {
                    AppendTextToTextBox("增大监听音量错误,错误信息:" + err_info);
                }
            }
            else
            {
                MessageBox.Show("产品串口未打开", "打开串口", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        /// <summary>
        /// 广播主机监听音量调小
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_TrunDownMornitorSource_Click(object sender, RoutedEventArgs e)
        {
            string err_info = string.Empty;
            if (StaticInfo.funProduct.isProductSerialPortOpen)
            {
                StaticInfo.funProduct.Function_Adjust_MornitorVolume(0, out err_info);//监听音量调小
                if (!string.IsNullOrEmpty(err_info))
                {
                    AppendTextToTextBox("减小监听音量错误,错误信息:" + err_info);
                }
            }
            else
            {
                MessageBox.Show("产品串口未打开", "打开串口", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        #endregion

        /// <summary>
        /// 故障信息转换
        /// </summary>
        /// <param name="status">故障状态</param>
        /// <returns>故障信息</returns>
        public static string BoolExcangeString(bool status)
        {
            string result = string.Empty;
            if (!status) result = "正常";
            else result = "故障";

            return result;
        }

        /// <summary>
        /// 按键有效结果判断
        /// </summary>
        /// <param name="number">按键字节</param>
        /// <param name="position">有效状态</param>
        /// <returns></returns>
        public static FunProduct.Key_Status IsKeyStatusSet(byte number, int position)
        {
            return (number & (1 << position)) != 0 ? FunProduct.Key_Status.Effective : FunProduct.Key_Status.Invalid;
        }
        /// <summary>
        /// TextBox末尾追加内容的方法
        /// </summary>
        /// <param name="textBoxName">TextBox控件名</param>
        /// <param name="textToAdd">显示的内容</param>
        public void AppendTextToTextBox(string textToAdd)
        {
            // 获取当前时间并格式化
            DateTime now = DateTime.Now;
            string timeFormat = $"{now:HH:mm}"; // 格式化时间
            string formattedTime = $"{timeFormat} ";
            string finalText = formattedTime + textToAdd + Environment.NewLine;
            double currentVerticalOffset = Txt_ManualTestResult.VerticalOffset;
            Txt_ManualTestResult.AppendText(finalText);
            Txt_ManualTestResult.ScrollToVerticalOffset(currentVerticalOffset);
        }
    }
}
